<template>
  <div class="life-history-tab">
    <!-- 生命时间轴 -->
    <a-row :gutter="24" class="timeline-section">
      <a-col :span="24">
        <a-card title="生命历程时间轴" size="small">
          <div class="life-timeline">
            <a-timeline mode="left">
              <!-- 出生事件 -->
              <a-timeline-item color="green">
                <template #dot>
                  <CalendarOutlined style="font-size: 16px" />
                </template>
                <div class="timeline-content">
                  <h4>出生</h4>
                  <p><strong>日期：</strong>{{ archive.lifeHistory?.birthDate || '未知' }}</p>
                  <p><strong>地点：</strong>{{ archive.basicInfo?.birthPlace || '未知' }}</p>
                  <a-tag color="green">生命起点</a-tag>
                </div>
              </a-timeline-item>

              <!-- 主要生命事件 -->
              <a-timeline-item v-for="event in getSortedMajorEvents()" :key="event.id" :color="getEventColor(event.type)">
                <template #dot>
                  <component :is="getEventIcon(event.type)" style="font-size: 16px" />
                </template>
                <div class="timeline-content">
                  <h4>{{ event.title }}</h4>
                  <p><strong>日期：</strong>{{ event.date }}</p>
                  <p><strong>描述：</strong>{{ event.description }}</p>
                  <a-space>
                    <a-tag :color="getImportanceColor(event.importance)">
                      {{ getImportanceText(event.importance) }}
                    </a-tag>
                    <a-tag>{{ getEventTypeText(event.type) }}</a-tag>
                  </a-space>
                  <div class="event-actions">
                    <a-button type="link" size="small" @click="editEvent(event)">
                      <EditOutlined />
                      编辑
                    </a-button>
                    <a-button type="link" size="small" danger @click="deleteEvent(event)">
                      <DeleteOutlined />
                      删除
                    </a-button>
                  </div>
                </div>
              </a-timeline-item>

              <!-- 死亡事件（如果已故） -->
              <a-timeline-item v-if="archive.status === 'dead'" color="red">
                <template #dot>
                  <StopOutlined style="font-size: 16px" />
                </template>
                <div class="timeline-content">
                  <h4>去世</h4>
                  <p><strong>日期：</strong>{{ archive.lifeHistory?.deathDate || '未知' }}</p>
                  <p><strong>享年：</strong>{{ archive.age }}岁</p>
                  <a-tag color="red">生命终点</a-tag>
                </div>
              </a-timeline-item>

              <!-- 添加新事件 -->
              <a-timeline-item color="blue" style="opacity: 0.6">
                <template #dot>
                  <PlusOutlined style="font-size: 16px" />
                </template>
                <div class="timeline-content">
                  <a-button type="dashed" @click="showAddEventModal = true"> 添加新的生命事件 </a-button>
                </div>
              </a-timeline-item>
            </a-timeline>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 成长轨迹 -->
    <a-row :gutter="24" class="growth-section">
      <a-col :span="12">
        <a-card title="成长轨迹" size="small">
          <div class="growth-chart">
            <div class="chart-header">
              <h4>业力变化曲线</h4>
            </div>
            <div class="karma-progress">
              <div v-for="track in getGrowthTrack()" :key="track.age" class="progress-item">
                <div class="age">{{ track.age }}岁</div>
                <div class="event">{{ track.event }}</div>
                <div class="karma-bar">
                  <a-progress :percent="Math.min(Math.max((track.karma + 100) / 2, 0), 100)" :stroke-color="getKarmaColor(track.karma)" size="small" :show-info="false" />
                  <span class="karma-value">{{ track.karma }}</span>
                </div>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>

      <a-col :span="12">
        <a-card title="人生成就" size="small">
          <div class="achievements">
            <div v-for="achievement in getAchievements()" :key="achievement" class="achievement-item">
              <a-tag color="gold">
                <TrophyOutlined />
                {{ achievement }}
              </a-tag>
            </div>
            <a-button type="dashed" block @click="showAddAchievement = true">
              <PlusOutlined />
              添加成就
            </a-button>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 婚姻家庭变迁 -->
    <a-row :gutter="24" class="marriage-section">
      <a-col :span="24">
        <a-card title="婚姻家庭变迁史" size="small">
          <a-table :columns="marriageColumns" :data-source="getMarriageHistory()" :pagination="false" size="small">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="record.status === '进行中' ? 'green' : 'gray'">
                  {{ record.status }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'actions'">
                <a-space>
                  <a-button type="link" size="small">
                    <EyeOutlined />
                    详情
                  </a-button>
                  <a-button type="link" size="small">
                    <EditOutlined />
                    编辑
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>

    <!-- 添加事件弹窗 -->
    <a-modal v-model:open="showAddEventModal" title="添加生命事件" @ok="handleAddEvent" @cancel="resetEventForm">
      <a-form ref="eventFormRef" :model="eventForm" :rules="eventRules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="事件标题" name="title">
              <a-input v-model:value="eventForm.title" placeholder="请输入事件标题" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="事件类型" name="type">
              <a-select v-model:value="eventForm.type">
                <a-select-option value="birth">出生</a-select-option>
                <a-select-option value="education">教育</a-select-option>
                <a-select-option value="career">职业</a-select-option>
                <a-select-option value="marriage">婚姻</a-select-option>
                <a-select-option value="family">家庭</a-select-option>
                <a-select-option value="achievement">成就</a-select-option>
                <a-select-option value="tragedy">悲剧</a-select-option>
                <a-select-option value="other">其他</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="事件日期" name="date">
              <a-date-picker v-model:value="eventForm.date" style="width: 100%" placeholder="请选择事件日期" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="重要程度" name="importance">
              <a-select v-model:value="eventForm.importance">
                <a-select-option value="low">低</a-select-option>
                <a-select-option value="medium">中</a-select-option>
                <a-select-option value="high">高</a-select-option>
                <a-select-option value="critical">极高</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="事件描述" name="description">
          <a-textarea v-model:value="eventForm.description" :rows="4" placeholder="请详细描述这个事件..." />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 添加成就弹窗 -->
    <a-modal v-model:open="showAddAchievement" title="添加人生成就" @ok="handleAddAchievement" @cancel="achievementText = ''">
      <a-input v-model:value="achievementText" placeholder="请输入成就内容" @press-enter="handleAddAchievement" />
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import { CalendarOutlined, BookOutlined, BankOutlined, HeartOutlined, HomeOutlined, TrophyOutlined, FrownOutlined, QuestionCircleOutlined, EditOutlined, DeleteOutlined, PlusOutlined, EyeOutlined, StopOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'

// 组件属性
const props = defineProps({
  archive: {
    type: Object,
    required: true
  }
})

// 组件事件
const emit = defineEmits(['update'])

// 响应式数据
const showAddEventModal = ref(false)
const showAddAchievement = ref(false)
const achievementText = ref('')
const eventFormRef = ref()

// 事件表单数据
const eventForm = reactive({
  title: '',
  type: 'other',
  date: null,
  importance: 'medium',
  description: ''
})

// 表单验证规则
const eventRules = {
  title: [{ required: true, message: '请输入事件标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
  date: [{ required: true, message: '请选择事件日期', trigger: 'change' }],
  description: [{ required: true, message: '请输入事件描述', trigger: 'blur' }]
}

// 婚姻历史表格列
const marriageColumns = [
  { title: '关系类型', dataIndex: 'type', key: 'type' },
  { title: '对象姓名', dataIndex: 'partner', key: 'partner' },
  { title: '开始日期', dataIndex: 'startDate', key: 'startDate' },
  { title: '结束日期', dataIndex: 'endDate', key: 'endDate' },
  { title: '状态', key: 'status' },
  { title: '操作', key: 'actions' }
]

// 计算属性和方法
const getSortedMajorEvents = () => {
  const events = props.archive.lifeHistory?.majorEvents || []
  return events.sort((a, b) => new Date(a.date) - new Date(b.date))
}

const getGrowthTrack = () => {
  return props.archive.lifeHistory?.growthTrack || []
}

const getAchievements = () => {
  return props.archive.lifeHistory?.achievements || []
}

const getMarriageHistory = () => {
  const spouse = props.archive.socialNetwork?.family?.spouse
  if (!spouse) return []

  return [
    {
      type: '婚姻',
      partner: spouse.name,
      startDate: '未知',
      endDate: spouse.status === 'alive' ? '-' : '未知',
      status: spouse.status === 'alive' ? '进行中' : '已结束'
    }
  ]
}

const getEventColor = (type) => {
  const colors = {
    birth: 'green',
    education: 'blue',
    career: 'purple',
    marriage: 'pink',
    family: 'orange',
    achievement: 'gold',
    tragedy: 'red',
    other: 'gray'
  }
  return colors[type] || 'gray'
}

const getEventIcon = (type) => {
  const icons = {
    birth: CalendarOutlined,
    education: BookOutlined,
    career: BankOutlined,
    marriage: HeartOutlined,
    family: HomeOutlined,
    achievement: TrophyOutlined,
    tragedy: FrownOutlined,
    other: QuestionCircleOutlined
  }
  return icons[type] || QuestionCircleOutlined
}

const getEventTypeText = (type) => {
  const texts = {
    birth: '出生',
    education: '教育',
    career: '职业',
    marriage: '婚姻',
    family: '家庭',
    achievement: '成就',
    tragedy: '悲剧',
    other: '其他'
  }
  return texts[type] || '未知'
}

const getImportanceColor = (importance) => {
  const colors = {
    low: 'default',
    medium: 'blue',
    high: 'orange',
    critical: 'red'
  }
  return colors[importance] || 'default'
}

const getImportanceText = (importance) => {
  const texts = {
    low: '普通',
    medium: '重要',
    high: '非常重要',
    critical: '关键节点'
  }
  return texts[importance] || '未知'
}

const getKarmaColor = (karma) => {
  if (karma >= 80) return '#52c41a'
  if (karma >= 40) return '#1890ff'
  if (karma >= 0) return '#faad14'
  if (karma >= -40) return '#fa541c'
  return '#f5222d'
}

// 事件操作方法
const editEvent = (event) => {
  Object.assign(eventForm, {
    ...event,
    date: dayjs(event.date)
  })
  showAddEventModal.value = true
}

const deleteEvent = (event) => {
  // 这里应该调用删除方法
  message.success('事件删除成功')
}

const handleAddEvent = async () => {
  try {
    await eventFormRef.value.validate()

    const eventData = {
      ...eventForm,
      date: eventForm.date.format('YYYY-MM-DD')
    }

    // 发送更新事件给父组件
    emit('update', eventData)

    message.success('生命事件添加成功')
    showAddEventModal.value = false
    resetEventForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const resetEventForm = () => {
  eventFormRef.value?.resetFields()
  Object.assign(eventForm, {
    title: '',
    type: 'other',
    date: null,
    importance: 'medium',
    description: ''
  })
}

const handleAddAchievement = () => {
  if (!achievementText.value.trim()) {
    message.warning('请输入成就内容')
    return
  }

  // 这里应该调用添加成就的方法
  message.success('成就添加成功')
  achievementText.value = ''
  showAddAchievement.value = false
}
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.life-history-tab {
  // 重写 Ant Design 组件样式以适应深色主题
  :deep(.ant-card) {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 12px;
    backdrop-filter: blur(10px);

    .ant-card-head {
      background: transparent;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      .ant-card-head-title {
        color: $text-primary;
        font-weight: 600;
      }
    }

    .ant-card-body {
      background: transparent;
      color: $text-primary;
    }
  }

  // Timeline 样式
  :deep(.ant-timeline) {
    .ant-timeline-item-head {
      background: transparent;
    }

    .ant-timeline-item-tail {
      border-left-color: rgba(255, 255, 255, 0.15);
    }

    .ant-timeline-item-content {
      color: $text-primary;
    }
  }

  // Table 样式
  :deep(.ant-table) {
    background: transparent;

    .ant-table-thead > tr > th {
      background: rgba(255, 255, 255, 0.08);
      border-bottom: 1px solid rgba(255, 255, 255, 0.15);
      color: $text-primary;
    }

    .ant-table-tbody > tr > td {
      background: transparent;
      border-bottom: 1px solid rgba(255, 255, 255, 0.05);
      color: $text-primary;
    }

    .ant-table-tbody > tr:hover > td {
      background: rgba(114, 46, 209, 0.05);
    }
  }

  // 表单样式
  :deep(.ant-modal) {
    .ant-modal-content {
      background: rgba(0, 0, 0, 0.8);
      backdrop-filter: blur(20px);
      border: 1px solid rgba(255, 255, 255, 0.15);
    }

    .ant-modal-header {
      background: transparent;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      .ant-modal-title {
        color: $text-primary;
      }
    }

    .ant-modal-body {
      background: transparent;
    }
  }

  :deep(.ant-form) {
    .ant-form-item-label > label {
      color: $text-primary;
    }

    .ant-input,
    .ant-input-number,
    .ant-select-selector,
    .ant-textarea,
    .ant-picker {
      background: rgba(255, 255, 255, 0.08);
      border: 1px solid rgba(255, 255, 255, 0.2);
      color: $text-primary;

      &:hover {
        border-color: $primary-color;
      }

      &:focus {
        border-color: $primary-color;
        box-shadow: 0 0 0 2px rgba(114, 46, 209, 0.2);
      }
    }

    .ant-btn {
      &.ant-btn-primary {
        background: $primary-color;
        border-color: $primary-color;

        &:hover {
          background: $primary-color-light;
          border-color: $primary-color-light;
        }
      }

      &.ant-btn-dashed {
        background: rgba(255, 255, 255, 0.05);
        border: 1px dashed rgba(255, 255, 255, 0.3);
        color: $text-secondary;

        &:hover {
          background: rgba(114, 46, 209, 0.1);
          border-color: $primary-color;
          color: $primary-color;
        }
      }

      &:not(.ant-btn-primary):not(.ant-btn-dashed) {
        background: rgba(255, 255, 255, 0.08);
        border: 1px solid rgba(255, 255, 255, 0.2);
        color: $text-primary;

        &:hover {
          background: rgba(114, 46, 209, 0.1);
          border-color: $primary-color;
          color: $primary-color;
        }
      }
    }
  }

  // Progress 样式
  :deep(.ant-progress) {
    .ant-progress-bg {
      background: rgba(255, 255, 255, 0.1);
    }
  }

  // Statistic 样式
  :deep(.ant-statistic) {
    .ant-statistic-title {
      color: $text-secondary;
    }

    .ant-statistic-content {
      color: $text-primary;
    }
  }

  .timeline-section {
    margin-bottom: $spacing-lg;

    .life-timeline {
      .timeline-content {
        h4 {
          margin: 0 0 $spacing-sm 0;
          color: #ffd700;
          font-weight: 500;
        }

        p {
          margin: $spacing-xs 0;
          font-size: 14px;
          color: $text-secondary;
        }

        .event-actions {
          margin-top: $spacing-sm;
        }
      }
    }
  }

  .growth-section {
    margin-bottom: $spacing-lg;

    .growth-chart {
      .chart-header {
        h4 {
          color: $primary-color;
          margin-bottom: $spacing-md;
        }
      }

      .karma-progress {
        .progress-item {
          display: flex;
          align-items: center;
          gap: $spacing-md;
          margin-bottom: $spacing-sm;
          padding: $spacing-xs;
          border-radius: 8px;
          background: rgba(255, 255, 255, 0.05);
          border: 1px solid rgba(255, 255, 255, 0.1);
          transition: all 0.3s ease;

          &:hover {
            background: rgba(255, 255, 255, 0.08);
            border-color: $primary-color;
          }

          .age {
            min-width: 40px;
            font-weight: 500;
            color: #ffd700;
          }

          .event {
            min-width: 80px;
            font-size: 12px;
            color: $text-secondary;
          }

          .karma-bar {
            flex: 1;
            display: flex;
            align-items: center;
            gap: $spacing-sm;

            .karma-value {
              min-width: 30px;
              font-size: 12px;
              font-weight: 500;
              color: $text-primary;
            }
          }
        }
      }
    }

    .achievements {
      .achievement-item {
        margin-bottom: $spacing-sm;

        .ant-tag {
          margin-bottom: $spacing-xs;
          background: rgba(255, 215, 0, 0.2);
          border: 1px solid rgba(255, 215, 0, 0.3);
          color: #ffd700;
        }
      }
    }
  }

  .marriage-section {
    .ant-table {
      font-size: 14px;
    }
  }
}

// 响应式样式
@media (max-width: 768px) {
  .life-history-tab {
    .growth-section {
      .ant-col {
        margin-bottom: $spacing-md;
      }
    }

    .karma-progress {
      .progress-item {
        flex-direction: column;
        align-items: flex-start !important;
        gap: $spacing-xs !important;

        .karma-bar {
          width: 100%;
        }
      }
    }
  }
}
</style>
